import Konva from "konva";
import { Draw } from "../../../Draw/Draw";
import { setStageCursor } from "./stage-cursor";
import { lineControlDragEnd } from "./line-control-dragend";
import { lineControlDragMove } from "./line-control-dragmove";
import { lineControlDragStart } from "./line-control-dragstart";
import { getColorMatch, getUniqueId, parseLinePoints } from "../../../Utils";

type IControl = { x: number; y: number };

/**
 * 设置某条直线选中状态 - 显示控制锚点
 * @param line
 * @param draw
 * @returns
 */
export function setLineSelected(line: Konva.Line, draw: Draw) {
  // 1. 拿到 layer
  const layer = draw.getLayer();
  if (!layer) return;

  // 解析 x y
  const { x, y } = line.position();
  // 设置选中
  line.setAttrs({ selected: true });

  // 3. 拿到所有锚点
  const controls: IControl[] = [];
  parseLinePoints(line.attrs.points).forEach((anchor) => {
    controls.push({ x: anchor[0], y: anchor[1] });
  });

  // 4. 添加锚点
  controls.forEach((control, index) => {
    // 创建控制点
    const circle = new Konva.Circle({
      controlIndex: index,
      id: getUniqueId(),
      name: "line-control",
      pid: line.id(), // parent ID (line)
      x: control.x + x, // 控制点要跟随线段
      y: control.y + y, // 控制点要跟随线段
      radius: 5,
      stroke: <string>getColorMatch(draw, "transformerColor"),
      fill: <string>getColorMatch(draw, "transformerColor"), // 控制点填充与colorScheme 的 形变节点一致
      strokeWidth: 1,
      draggable: true,
    });

    // 添加 control 事件
    circle.on("dragend", (e) => lineControlDragEnd(e, draw));
    circle.on("dragstart", () => lineControlDragStart(draw));
    circle.on("dragmove", (e) => lineControlDragMove(e, draw));
    circle.on("mouseenter", () => setStageCursor(draw, "pointer"));
    circle.on("mouseleave", () => setStageCursor(draw, "default"));

    // 添加控制点到 layer
    draw.getKonvaGraph().addShape({ shape: circle });
  });
}
